#include <iostream>
#include <signal.h>
#include <unistd.h>

void PrintPending(sigset_t &pending)
{
    std::cout << "cur process[" << getpid() << "]pending! ";
    for (int i = 31; i > 0; i--)
    {
        if (sigismember(&pending, i))
        {
            std::cout << '1';
        }
        else
        {
            std::cout << '0';
        }
    }
    std::cout << std::endl;
}

void handler(int sig)
{
    std::cout << sig << "号信号被递达了...." << std::endl;
    std::cout << "-------------------------------" << std::endl;
    sigset_t pending;
    sigpending(&pending);
    PrintPending(pending);
    std::cout << "-------------------------------" << std::endl;
}

int main()
{
    signal(2, handler);
    // 1、创还能sigset_t
    sigset_t block_set, old_set;
    // 2、初始化
    sigemptyset(&block_set);
    sigemptyset(&old_set);
    // 3、将2号信号给设置到block_set
    sigaddset(&block_set, 2);
    // 4、将block_set的数据写到block表
    sigprocmask(SIG_BLOCK, &block_set, &old_set);

    int cnt = 15;
    while (true)
    {
        // 5、获取pending表
        sigset_t pending;
        sigpending(&pending);

        // 隔一秒打印一次pending
        PrintPending(pending);
        sleep(1);

        if (cnt == 0)
        {
            std::cout << "解除对2号信号的屏蔽...." << std::endl;
            sigprocmask(SIG_SETMASK, &old_set, nullptr);
        }
        cnt--;
    }

    return 0;
}
